<script setup lang="ts">
import html2canvas from 'html2canvas'
import { ref } from 'vue'
import wx from 'weixin-js-sdk'

// const cards = [
//   {
//     id: 1,
//     image: '/assets/images/qiufu/shengyi.png',
//     description: '/assets/images/qiufu/shengyi-desc.png'
//   },
//   {
//     id: 2,
//     image: '/assets/images/qiufu/pingan.png',
//     description: '/assets/images/qiufu/pingan-desc.png'
//   },
//   {
//     id: 3,
//     image: '/assets/images/qiufu/xiaohai.png',
//     description: '/assets/images/qiufu/xiaohai-desc.png'
//   }
// ];

const imageList = [
  '/assets/images/qiufu/border-fu1.png',
  '/assets/images/qiufu/border-fu2.png',
  '/assets/images/qiufu/border-fu3.png',
]
const timer1 = ref()
const loading = ref(false)
const flag = ref(false)

const isSubmit = ref(false)
const msg = ref()
const showDownloadPopup = ref(false)
const isMobile = ref(false)

const orderId = ref(0)
const userInfo = useUserInfoState()

const isWxConfigured = ref(false)

const isPaying = ref(false)

function checkDevice() {
  const userAgent = navigator.userAgent.toLowerCase()
  // 常见的手机端的 userAgent 字符串判断
  const mobileKeywords = ['iphone', 'ipod', 'android', 'windows phone', 'blackberry', 'webos']

  isMobile.value = mobileKeywords.some(keyword => userAgent.includes(keyword))
}

const currentIndex = ref(0)

const router = useRouter()

const username = ref('张三')

const number = ref('123456789')

// 判断是否为微信浏览器
const isWeChat = () => /MicroMessenger/i.test(navigator.userAgent)
function prevImage() {
  currentIndex.value = (currentIndex.value - 1 + imageList.length) % imageList.length
}

function nextImage() {
  currentIndex.value = (currentIndex.value + 1) % imageList.length
}

const cards = ref()

async function getFuList() {
  const { data: res } = await useFetchPost('/api/Fu/getFuList')
  cards.value = res.value.data.list.map((item: any) => {
    return {
      id: Number(item.id),
      name: item.name,
      image: item.img,
      description: item.desc,
      price: item.price,
    }
  })
}

const flippedCards = ref<number[]>([])
const showPopup = ref(false)
const showPay = ref(false)
const selectedCardId = ref<number | null>(null)

const form = ref({
  name: '',
  address: '',
  type: '1', // 1: 自己求符, 2: 为他人求符
})

const qrCodeUrl = ref('')

const showQRCodeModal = ref(false)

function toggleCard(id: number) {
  if (flippedCards.value.includes(id)) {
    flippedCards.value = flippedCards.value.filter(cardId => cardId !== id)
  }
  else {
    flippedCards.value.push(id)
  }
}

async function submitPayWx() {
  if (isPaying.value)
    return // 防止重复点击
  isPaying.value = true
  if (!orderId.value) {
    msg.value = '订单创建失败，请稍后再试'
    isSubmit.value = true
  }
  try {
    let method
    if (isMobile.value && isWeChat()) {
      method = 'mp'
    }
    else if (isMobile.value) {
      method = 'wap'
    }
    else {
      method = 'scan'
    }
    const oid = orderId.value
    const { data: res } = await useFetchPost('/api/Orders/payOrder', {
      oid,
      user_id: userInfo.value.id,
      returnurl: `${useRequestURL().href}?oid=${oid}`,
      type: 'wechat',
      method,
    })
    if (!res.value || !res.value.data) {
      msg.value = '未获取到订单信息或者订单已支付'
      isSubmit.value = true
      return
    }
    const info = res.value.data
    if (!isWxConfigured.value) {
      wx.config({
        debug: false, // 开启调试模式，调试时为true
        appId: info.appId, // 公众号的唯一标识
        timestamp: info.timeStamp, // 时间戳
        nonceStr: info.nonceStr, // 随机串
        signature: info.paySign, // 签名
        jsApiList: ['chooseWXPay'], // 需要调用的JS接口
      })
      isWxConfigured.value = true
    }

    if (isMobile.value && isWeChat()) {
      const wxReadyTimeout = setTimeout(() => {
        msg.value = '微信支付初始化失败，请刷新页面重试'
        isSubmit.value = true
        isPaying.value = false
      }, 5000)

      wx.ready(() => {
        clearTimeout(wxReadyTimeout) // 成功准备则清除
        // 调用支付接口
        wx.chooseWXPay({
          timestamp: info.timeStamp, // 支付签名时间戳
          nonceStr: info.nonceStr, // 支付签名随机串
          package: info.package, // 预支付交易会话ID
          signType: info.signType, // 签名方式，默认为'SHA1'，使用 MD5 签名时请注意
          paySign: info.paySign, // 支付签名
          success(res: any) {
            // 支付成功后的回调
            console.log('支付成功', res)
            msg.value = '求符成功'
            isSubmit.value = true
            flag.value = true
          },
          fail(res: any) {
            // 支付失败的回调
            console.log('支付失败', res)
            msg.value = '支付失败'
            isSubmit.value = true
          },
          complete() {
            isPaying.value = false
          },
        })
      })

      wx.error((res: any) => {
        // 错误回调
        console.error('微信 SDK 错误:', res)
        msg.value = '微信支付初始化失败'
        isSubmit.value = true
        isPaying.value = false
      })
    }
    else if (isMobile.value) {
      window.location.href = info.targetUrl
    }
    else {
      // 非微信浏览器，显示二维码
      qrCodeUrl.value = info.qrCodeBase64
      showQRCodeModal.value = true
      timer1.value = setInterval(async () => {
        loading.value = true
        try {
          const { data: res } = await useFetchPost('/api/orders/getOrderInfo', {
            oid,
          })
          if (res.value.data.status == 1) {
            if (timer1.value) {
              clearInterval(timer1.value)
            }
            closeModal()

            msg.value = '求符成功！'
            isSubmit.value = true
          }
        }
        catch (error) {
          console.error('Error fetching order info:', error)
        }
        finally {
          loading.value = false
        }
      }, 1000)
    }
  }
  catch (e) {
    console.error('支付异常:', e)
    msg.value = '支付请求失败，请稍后再试'
    isSubmit.value = true
  }
  finally {
    isPaying.value = false
  }
}

async function submitPayZfb() {
  if (isPaying.value)
    return
  isPaying.value = true

  try {
    let method
    if (isMobile.value && isWeChat()) {
      method = 'mp'
    }
    else if (isMobile.value) {
      method = 'wap'
    }
    else {
      method = 'web'
    }
    const oid = orderId.value
    const { data: res } = await useFetchPost('/api/Orders/payOrder', {
      oid,
      user_id: userInfo.value.id,
      returnurl: `${useRequestURL().href}?oid=${oid}`,
      type: 'alipay',
      method,
    })

    if (!res.value || !res.value.data || !res.value.data.targetUrl) {
      msg.value = '未获取到支付信息，请稍后再试'
      isSubmit.value = true
      return
    }

    // 插入 form 并执行
    const wrapper = document.createElement('div')
    wrapper.innerHTML = res.value.data.targetUrl
    document.body.appendChild(wrapper)

    // 有些浏览器安全策略会阻止 inline script 执行，需要手动触发
    const form = wrapper.querySelector('form') as HTMLFormElement | null
    if (form) {
      form.submit()
    }
    else {
      msg.value = '支付表单解析失败'
      isSubmit.value = true
    }
  }
  catch (err) {
    console.error('支付宝支付异常:', err)
    msg.value = '请求失败，请稍后再试'
    isSubmit.value = true
  }
  finally {
    isPaying.value = false
  }
}

function isFlipped(id: number) {
  return flippedCards.value.includes(id)
}

const selectedImg = ref()

function qiufuEvent(obj: any) {
  selectedCardId.value = obj.id
  selectedImg.value = obj.image
  showPopup.value = true
}

// 关闭弹窗
function closeModal() {
  showPopup.value = false
  showPay.value = false
  showQRCodeModal.value = false
  // 重置表单
  form.value = {
    name: '',
    address: '',
    type: '1',
  }
}
// 关闭提示
function closeMsgModal() {
  if (flag.value == false)
    return
  showDownloadPopup.value = true
  showQRCodeModal.value = false
  isPaying.value = false
  showPay.value = false
}
async function payType() {
  const { data: res } = await useFetchPost('/api/Qiufu/qiufu', {
    data: {
      cardId: selectedCardId.value,
      ...form.value,
    },
    user_id: userInfo.value.id,
  })
  orderId.value = res.value.data.oid
  showPopup.value = false
  showPay.value = true
}

// 提交
async function submit() {
  // msg.value = '求符成功'
  // isSubmit.value = true
  // flag.value = true
  // return
  // console.log('提交的表单数据：', {
  //   cardId: selectedCardId.value,
  //   ...form.value
  // })
  const { data: res } = await useFetchPost('/api/Qiufu/qiufu', {
    data: {
      cardId: selectedCardId.value,
      ...form.value,
    },
  })
  orderId.value = res.value.data.oid
  // TODO: 调用API提交数据
  closeModal()
  showPay.value = true
}
const isDownloading = ref(false)
async function down() {
  if (isDownloading.value)
    return
  try {
    isDownloading.value = true

    // 显示加载状态
    msg.value = '生成图片中...'
    isSubmit.value = true

    // 确保DOM更新完成
    await nextTick()
    // 获取当前轮播项的DOM元素
    const carouselItem = document.querySelectorAll('.image-container')[currentIndex.value]

    // 使用 html2canvas 截图
    const canvas = await html2canvas(carouselItem as HTMLElement, {
      useCORS: true, // 允许跨域图片
      scale: 5, // 提高分辨率
      logging: false, // 关闭日志
      backgroundColor: null, // 透明背景
    })

    // 转换为可下载的图片
    const imgData = canvas.toDataURL('image/png')

    // 创建临时链接
    const link = document.createElement('a')
    link.download = `护身符-${Date.now()}.png`
    link.href = imgData

    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 关闭弹窗
    showDownloadPopup.value = false
  }
  catch (error) {
    console.error('下载失败:', error)
    msg.value = '下载失败，请重试'
    isSubmit.value = true
  }
  finally {
    isDownloading.value = false
  }
}
const route = useRoute()
const cardIds = ref<string[]>([])

const cardData = ref<cardStruct[]>()
onMounted(async () => {
  checkDevice()
  // 预加载所有图片
  const preloadImages = [...imageList, selectedImg.value]
  preloadImages.forEach((img) => {
    new Image().src = img
  })
  await getFuList()
  const { data: res } = await useFetchPost('/api/orders/getQiufuCardId', {
    type: 3,
    user_id: userInfo.value.id,
  })
  cardIds.value = res.value.data.map((item: any) => item.cardId)
  cardData.value = res.value.data
})

interface cardStruct {
  cardId: string
  name: string
  address: string
  type: string
}
function showDown(card: any) {
  selectedCardId.value = card.id
  selectedImg.value = card.image
  showDownloadPopup.value = true
  const exists = cardData.value?.find(item => item.cardId === String(card.id))
  if (exists) {
    username.value = exists.name
    const characters = '0123456789'
    let result = ''
    for (let i = 0; i < 9; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length)
      result += characters[randomIndex]
    }
    number.value = `kqg${result}`
  }
}
</script>

<template>
  <div class="min-h-screen w-full relative">
    <Header back="/select" />
    <img
      src="/assets/images/qiufu/qiufuye.png"
      alt=""
      class="h-auto w-full object-contain"
    >
    <div class="top-1/2 writing-vertical -translate-y-1/2 transform right-0 fixed z-50">
      <button
        class="text-white px-2 py-1 rounded-l-lg bg-black/60 transition hover:bg-gray-800"
        @click="router.push('orders')"
      >
        查看订单
      </button>
    </div>
    <div class="inset-0 bottom-[3%] top-[22%] absolute">
      <div class="mx-auto px-4 h-full container">
        <div class="gap-4 grid grid-cols-2 h-full">
          <div
            v-for="(card, index) in cards"
            :key="card.id"
            class="opacity-0 h-full cursor-pointer relative animate-fade-in-up"
            :style="{ animationDelay: `${index * 300}ms` }"
            @click="toggleCard(card.id)"
          >
            <!-- 外层提供 perspective -->
            <div class="h-full w-full [perspective:1000px]">
              <!-- 可翻转容器 -->
              <div
                class="h-full w-full transition-transform duration-500 [transform-style:preserve-3d] relative"
                :class="{ '[transform:rotateY(180deg)]': isFlipped(card.id) }"
              >
                <!-- 正面 -->
                <div class="h-full w-full [backface-visibility:hidden] absolute">
                  <img
                    :src="card.image"
                    class="rounded-lg h-full w-full shadow-lg object-contain"
                    alt=""
                  >
                </div>
                <!-- 背面 -->
                <div class="h-full w-full [backface-visibility:hidden] [transform:rotateY(180deg)] absolute">
                  <div class="h-full w-full relative">
                    <img
                      :src="card.description"
                      class="rounded-lg h-full w-full shadow-lg object-contain"
                      alt=""
                    >
                    <div class="pb-4 flex bottom-0 left-0 right-0 justify-center absolute">
                      <button v-if="cardIds.includes(String(card.id))" class="flex items-center justify-center" @click="showDown(card)">
                        <img src="/assets/images/qiufu/dl-button.png" alt="" class="h-6">
                      </button>
                      <button
                        v-else
                        class="bg-[url('/assets/images/qiufu/common-b.png')] w-[60%] bg-contain bg-center bg-no-repeat"
                        @click.stop="qiufuEvent(card)"
                      >
                        <span class="glow-text text-white">¥ {{ card.price }}</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 求符弹窗 -->
    <div
      v-if="showPopup"
      class="opacity-0 flex delay-[100ms] items-center inset-0 justify-center fixed z-2 animate-fade-in-up"
    >
      <div class="bg-black bg-opacity-50 inset-0 fixed" @click="closeModal" />
      <div class="max-w-md w-9/10 relative">
        <!-- 背景图 -->
        <img
          src="/assets/images/qiufu/form.png"
          alt=""
          class="h-auto w-full"
        >

        <!-- 关闭按钮 -->
        <button
          class="text-white transition-colors right-4 top-4 absolute z-10 hover:text-gray-200"
          @click="closeModal"
        >
          <UIcon name="i-heroicons-x-mark" class="text-2xl" />
        </button>

        <!-- 表单内容 -->
        <div class="mt-[12%] px-4 flex flex-col w-[90%] items-center inset-0 justify-center absolute">
          <UForm :state="form" class="max-w-[80%] w-full space-y-4">
            <div class="space-y-2">
              <URadio
                v-model="form.type"
                value="1"
                color="amber"
              >
                <template #label>
                  <span class="text-[#8f3c30]">为自己求护身符</span>
                </template>
              </URadio>
              <URadio
                v-model="form.type"
                value="2"
                color="amber"
              >
                <template #label>
                  <span class="text-[#8f3c30]">为他人求护身符</span>
                </template>
              </URadio>
              <UInput
                v-model="form.name"
                class="w-full"
                placeholder="姓名"
                color="amber"
                :style="{ color: 'black' }"
              />
              <UInput
                v-model="form.address"
                class="w-full"
                placeholder="现生活所在地"
                color="amber"
                :style="{ color: 'black' }"
              />
            </div>
          </UForm>
        </div>

        <!-- 确定按钮 -->
        <div class="flex bottom-16 left-0 right-0 justify-center absolute">
          <button class="flex items-center justify-center" @click="payType">
            <img src="/assets/images/qiufu/submit.png" alt="" class="h-8">
          </button>
        </div>
      </div>
    </div>

    <!-- <div v-if="showPay" class="absolute inset-0 bg-black/50 rounded-[inherit]"></div> -->
    <div
      v-if="showPay"
      class="mx-auto opacity-0 flex w-full delay-[100ms] items-center inset-0 left-0 right-0 justify-center fixed z-2 animate-fade-in-up md:w-1/2"
    >
      <div class="mx-auto bg-black bg-opacity-50 w-full inset-0 left-0 right-0 fixed md:w-[90%]" @click="closeModal" />
      <div class="mx-auto w-[80%] left-0 right-0 relative">
        <img
          src="/assets/images/fengshui/border-pay.png"
          alt=""
          class="w-full object-contain"
        >
        <!-- 蒙版层 -->
        <!-- 中间内容叠加展示 -->
        <div class="top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/3 w-[90%] absolute">
          <div class="flex flex-col gap-3 items-center">
            <div class="p-4 pb-3 border-b border-gray-500 flex items-center justify-between" @click="submitPayWx">
              <div class="w-[30%]">
                <img
                  src="/assets/images/wx-icon.png"
                  alt=""
                  class="h-auto w-full object-contain"
                >
              </div>
              <div class="w-[30%]">
                <img
                  src="/assets/images/wx-bt.png"
                  class="h-auto w-full object-contain"
                >
              </div>
            </div>
            <div v-if="!isWeChat()" class="p-4 flex items-center justify-between" @click="submitPayZfb">
              <div class="w-[30%]">
                <img
                  src="/assets/images/zfb-icon.png"
                  class="h-auto w-full object-contain"
                >
              </div>
              <div class="w-[30%]">
                <img
                  src="/assets/images/zfb-bt.png"
                  class="h-auto w-full object-contain"
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <TipModal
      v-model="isSubmit"
      title="提示"
      :message="msg"
      @close="closeMsgModal"
    />
    <TipModal
      v-model="showQRCodeModal"
      title="提示"
      message="请打开微信扫码支付"
      :image="qrCodeUrl"
      @close="closeMsgModal"
    />
    <div
      v-show="showDownloadPopup"
      class="opacity-0 flex delay-[100ms] items-center inset-0 justify-center fixed z-2 animate-fade-in-up"
    >
      <div class="bg-black bg-opacity-50 inset-0 fixed" @click="closeModal" />
      <div class="max-w-md w-[75%] relative">
        <!-- 背景图 -->
        <img
          src="/assets/images/qiufu/download.png"
          alt=""
          class="h-auto w-full object-contain"
        >

        <!-- 图片轮播展示区域 -->
        <!-- 修改后的轮播项结构 -->
        <div class="flex items-center inset-0 justify-center absolute overflow-hidden">
          <div
            class="flex w-full transition-transform duration-500 ease-in-out"
            :style="{ transform: `translateX(-${currentIndex * 100}%)` }"
          >
            <div
              v-for="(img, index) in imageList"
              :key="index"
              class="flex flex-shrink-0 w-full transition-all duration-500 items-center justify-center"
            >
              <div class="image-container grid w-[45%] place-items-center relative" :class="`carousel-item-${index}`">
                <img
                  :src="img"
                  class="rounded-lg shadow-md transition-all duration-300 relative"
                  :class="{
                    'w-full scale-100': index === currentIndex,
                    'w-[90%] opacity-60 scale-90': index !== currentIndex,
                  }"
                >
                <div class="text-size-2 left-1 top-1 absolute">
                  {{ username }}
                </div>
                <img
                  v-show="index === currentIndex"
                  :src="selectedImg"
                  class="w-[70%] absolute z-50"
                  style="top: 50%; left: 50%; transform: translate(-50%, -50%);"
                >
                <div class="text-size-2 bottom-1 left-1 absolute">
                  编号：{{ number }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="px-6 flex w-full pointer-events-none items-center inset-0 justify-between absolute">
          <img
            src="/assets/images/qiufu/left.png"
            alt="Left"
            class="w-[15%] cursor-pointer pointer-events-auto"
            @click="prevImage"
          >
          <img
            src="/assets/images/qiufu/right.png"
            alt="Right"
            class="w-[15%] cursor-pointer pointer-events-auto"
            @click="nextImage"
          >
        </div>

        <div class="flex items-center right-5 top-5 justify-end absolute">
          <button
            class="text-black transition-colors z-3 hover:text-gray-200"
            @click="showDownloadPopup = false"
          >
            <UIcon name="i-heroicons-x-mark" class="text-2xl" />
          </button>
        </div>

        <div class="mx-auto flex bottom-[10%] left-0 right-0 justify-center absolute">
          <button class="flex items-center justify-center" @click="down()">
            <img src="/assets/images/qiufu/dl-button.png" alt="" class="h-8">
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 自定义淡入上升动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 注册Tailwind动画 */
.animate-fade-in-up {
  animation: fadeInUp 0.1s ease-out forwards;
}

/* 定义延迟类 */
.delay-\[100ms\] {
  animation-delay: 100ms;
}

.glow-text {
  text-shadow: 0 0 8px rgba(255, 215, 0, 1);
}

img {
  transition:
    transform 0.3s ease,
    opacity 0.3s ease;
}

/* 确保截图区域可见 */
/* .image-container {
      width: 100%;
      height: 100%;
    } */

/* 隐藏非活动项（提升截图性能） */
.carousel-item:not(.active) {
  display: none;
}

.writing-vertical {
  writing-mode: vertical-rl;
  text-orientation: upright;
  letter-spacing: 0.1em;
  line-height: 1.4;
}
</style>
